package com.cskaoyan.market.shiro;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.admin.MarketAuthService;
import com.cskaoyan.market.service.admin.MarketRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName AdminRealm
 * @Description
 * @Author MZ
 * @Date 2023/5/25 8:58
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    MarketAuthService adminAuthService;
    @Autowired
    MarketRoleService roleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("管理员认证，应当访问market_admin表");
        //模拟认证通过
        // 用户名密码认证
        // TODO:admin登陆验证逻辑
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = adminAuthService.checkPasswordByUsername(username);

        return new SimpleAuthenticationInfo(username, password, getName());
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //固定写死，这个权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 动态获得角色权限
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
        Integer[] roleIds = admin.getRoleIds();
        Set<String> assignedPermissions = new HashSet<>();
        for (Integer roleId : roleIds) {
            Set<String> permissions = roleService.getPermissions(roleId);
            assignedPermissions.addAll(permissions);
        }
        for (String permission : assignedPermissions) {
            authorizationInfo.addStringPermission(permission);
        }
        return authorizationInfo;
    }


}
